from flask import Blueprint, render_template, redirect, url_for, flash, request, session
from flask_login import login_user, logout_user, login_required, current_user
from ...models import User, db
from ...forms import LoginForm, RegisterForm, EmailVerificationForm
from ...utils import send_verification_email, verify_captcha

# 创建蓝图
auth_zyy = Blueprint('auth_zyy', __name__)

@auth_zyy.route('/login_zyy', methods=['GET', 'POST'])
def login_zyy():
    """登录路由"""
    if current_user.is_authenticated:
        return redirect(url_for('main_zyy.index_zyy'))
    
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user and user.check_password(form.password.data):
            login_user(user)
            next_page = request.args.get('next')
            return redirect(next_page or url_for('main_zyy.index_zyy'))
        flash('用户名或密码错误', 'danger')
    return render_template('auth_zyy/login_zyy.html', form=form)

@auth_zyy.route('/register_zyy', methods=['GET', 'POST'])
def register_zyy():
    """注册路由"""
    if current_user.is_authenticated:
        return redirect(url_for('main_zyy.index_zyy'))
    
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(
            username=form.username.data,
            email=form.email.data
        )
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        
        # 发送验证码
        send_verification_email(user.email, user.username)
        session['email'] = user.email
        
        flash('注册成功！请查收验证邮件完成注册。', 'success')
        return redirect(url_for('auth_zyy.verify_email_zyy'))
    return render_template('auth_zyy/register_zyy.html', form=form)

@auth_zyy.route('/verify_email_zyy', methods=['GET', 'POST'])
def verify_email_zyy():
    """邮箱验证路由"""
    if current_user.is_authenticated:
        return redirect(url_for('main_zyy.index_zyy'))
    
    email = session.get('email')
    if not email:
        return redirect(url_for('auth_zyy.register_zyy'))
    
    form = EmailVerificationForm()
    if form.validate_on_submit():
        if verify_captcha(email, form.captcha.data):
            user = User.query.filter_by(email=email).first()
            user.email_verified = True
            db.session.commit()
            flash('邮箱验证成功！请登录。', 'success')
            session.pop('email', None)
            return redirect(url_for('auth_zyy.login_zyy'))
        flash('验证码错误或已过期', 'danger')
    return render_template('auth_zyy/verify_email_zyy.html', form=form)

@auth_zyy.route('/logout_zyy')
@login_required
def logout_zyy():
    """登出路由"""
    logout_user()
    flash('您已成功登出', 'success')
    return redirect(url_for('main_zyy.index_zyy')) 